package com.his.server.utils.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.his.server.consts.ServerConsts;
import com.his.server.exception.ConfigurationException;

public class EnvironmentProperties
{
	
    private static final Log logger;
    private Properties props;
    private List <Properties> propsList;
    private static EnvironmentProperties eproperties;
    
	static 
    {
        logger = LogFactory.getLog(EnvironmentProperties.class);
    }
	
    private EnvironmentProperties()
    {
        props = new Properties();
        propsList = new ArrayList <Properties> ();
    }
    

    public static void getInstance()
    {
    	if(logger.isTraceEnabled())
    		logger.trace("EnvironmentProperties_Start");
    	
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        eproperties = loadProperties(classLoader, ServerConsts.RESOURCE_PATH, ServerConsts.MAIN_RESOURCE_NAME);
        
        for (int i = 0; i < eproperties.props.size(); i++) {
        	String fName =eproperties.props.getProperty(String.valueOf(i));
        	eproperties.propsList.add(loadProperties(classLoader, ServerConsts.RESOURCE_PATH, fName).props);
        }
    	if(logger.isTraceEnabled())
    		logger.trace("EnvironmentProperties_End");
    }
    
    public List <Properties> getPropertyList()
    {
        return propsList;
    }
    
    public static EnvironmentProperties getEproperties()
    {
        return eproperties;
    }
    
    private static EnvironmentProperties loadProperties(ClassLoader loader, String propertiesPath, String fName)
    {
        EnvironmentProperties eproperties = new EnvironmentProperties();
        InputStream instream = null;
        StringBuffer fileName = new StringBuffer();
        fileName.append(propertiesPath).append(fName);
    	
		try {
			instream = loader.getResourceAsStream(fileName.toString());
			eproperties.props.load(instream);
		} catch (IOException ex) {
			throw new ConfigurationException(
					"IO Exception occured in loading default environment properties.",
					ex);
		}

		return eproperties;	 
    }
}
